// IntentService dies when finished
// has its own thread but dies when finished
// whereas service doesn't have its own thread(runs on main thread) but can live forever consequently
package com.bren.android.androidproject;

import java.util.Calendar;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.media.AudioManager;
import android.preference.PreferenceManager;

public class ScheduleService extends IntentService{// intent service has its own thread
	
	final CharSequence[] days={"Sunday","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
	SQLiteDatabase db=null;
	Cursor result=null;
		
	public ScheduleService() {
		super("ScheduleService");		
	}
	
	// onStartCommand should not be overridden for IntentService
	// should store schedule number that is currently keeping ringer off so we can display on UI
	
	
	protected void onPostExecute(Void result) {
		android.util.Log.w("ScheduleService","ScheduleServiceStoped");
	}
	// starts a single worker thread off main thread
	protected void onHandleIntent(Intent intent) {

		Calendar now=Calendar.getInstance();
		int dayValue=now.get(Calendar.DAY_OF_WEEK);
		int hourValue=now.get(Calendar.HOUR_OF_DAY);
		int minuteValue=now.get(Calendar.MINUTE);
		
		String day = String.valueOf(days[dayValue-1]);
		int t=hourValue*100+minuteValue;
		String time=String.valueOf(t);
		
		android.util.Log.w("ScheduleService", "ScheduleServiceStarted");
		android.util.Log.w("Time now:", day + " " + time);
				
		AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);	
		startDb();	
		SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this);
		
		String[] selectionArgs={day,time,time};
		result = db.query("schedule", new String [] {"day","start","finish"},
				"day=? AND (?>=start AND ?<finish)", selectionArgs, null, null, null);
		// if scheduling disabled then we still need to turn back on but shouldn't switch off
		// is within schedule? include start minute but excluding finish minute
		if(result.getCount()>0) {
			android.util.Log.w("ScheduleService","ScheduleActive");
			result.moveToFirst();
			android.util.Log.w("Schedule", result.getString(0)+" "+result.getInt(1)+"-"+result.getInt(2));
			android.util.Log.w("ScheduleStatus",(new Boolean(prefs.getBoolean("schedulestatus", true)).toString()));			
			
			if(new Boolean(prefs.getBoolean("schedulestatus", true))) {		
				if (audioManager.getRingerMode()==AudioManager.RINGER_MODE_NORMAL) {
					// if ringer on then turn off and note this
					Editor ed= prefs.edit();
					ed.putBoolean("scheduleswitch", true);
					ed.commit();
					android.util.Log.w("ScheduleService","switched to silent");
					audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
				}else{
					// it was already off, just note that we did not have to turn off
					Editor ed= prefs.edit();
					ed.putBoolean("scheduleswitch", false);
					ed.commit();
					android.util.Log.w("ScheduleService","already silent/vibrate");
				}			
			}
		}else {
			// if we turned off then turn on
			if(prefs.getBoolean("scheduleswitch", true)) {
				Editor ed= prefs.edit();
				ed.putBoolean("scheduleswitch", false);
				ed.commit();
				android.util.Log.w("ScheduleService","switched to normal(Out of Schedule)");
				audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
			}	
		}// end
		//stopDb();	
	}
	
	protected void startDb() {
		try {
			db=(new Database(this).getWritableDatabase());// this=getContext()
			android.util.Log.w("ScheduleService", "Database open");
		} catch (SQLiteException e) {
			android.util.Log.e("ScheduleService","Cannot open database");
		}	
	}
	
	protected void stopDb() {
		try {
			if(result!=null) {
				if(!result.isClosed()) {
					result.close();
				}	
				result=null;
			}
			if(db!=null) {
				if(db.isOpen()) {
					db.close();
				}
				db=null;
			}
			android.util.Log.w("ScheduleService","Database closed");
		}catch (SQLiteException e) {
			android.util.Log.e("ScheduleService","Cannot close database");
		}
	}
	
	public void onDestroy() {
		super.onDestroy();
		stopDb();		
	} 
}
